package ch.ethz.inf.shop.model.simpleDatabase.operators;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import ch.ethz.inf.shop.model.simpleDatabase.Tuple;

/**
 * An empty sort operator For the purposes of the project, you can consider only
 * string comparisons of the values.
 */
public class Sort extends Operator {

	private final ArrayList<Tuple> sortBuffer;
	private int cursor = 0;

	public Sort(final Operator op, Comparator<Tuple> compareFunction) {

		this.sortBuffer = new ArrayList<Tuple>();

		// construct sortBuffer
		// 1) fetch _all_ tuples from this.op and store them in sort buffer
		while (op.moveNext())
			sortBuffer.add(op.current());

		// 2) sort the buffer
		Collections.sort(this.sortBuffer, compareFunction);

	}

	@Override
	public boolean moveNext() {

		if (cursor < sortBuffer.size()) {
			current = sortBuffer.get(cursor);
			cursor++;
			return true;
		}

		return false;
	}

}
